package br.com.cdto.ldm;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import br.com.cdto.entity.Receptor;

public class ReceptorLDM extends LazyDataModel<Receptor>{
	private static final long serialVersionUID = -2741553413817878470L;
	
	private List<Receptor> lista;

	public ReceptorLDM(List<Receptor> lista) {
		this.lista = lista;
	}

	@Override
	public Object getRowKey(Receptor object) {
		return object.getPosicaoLista();
	}

	@Override
	public Receptor getRowData(String rowKey) {
		for (Receptor receptor : lista) {
			if (receptor.getId().toString().equals(rowKey)) {
				return receptor;
			}
		}
		return null;
	}

	@Override
	public List<Receptor> load(int first, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {
		List<Receptor> data = new ArrayList<Receptor>();

		for (Receptor receptor : lista) {
			boolean match = true;
			for (Iterator<String> it = filters.keySet().iterator(); it
					.hasNext();) {
				try {
					String filterProperty = it.next();
					String filterValue = filters.get(filterProperty);
					String fieldValue = null;
					if(filterProperty.equals("id")){
						fieldValue = String.valueOf(receptor.getId());
					}
					if(filterProperty.equals("rgct")){
						fieldValue = receptor.getRGCT();
					}
					if(filterProperty.equals("status")){
						fieldValue = receptor.getStatus();
					}
					if(filterProperty.equals("criterio")){
						fieldValue = String.valueOf(receptor.getCriterioGravidade());
					}
					if(filterProperty.equals("dataInsc")){
						fieldValue = String.valueOf(receptor.getDataInscricao().getTime());
					}
					if (filterValue == null
							|| fieldValue.startsWith(filterValue)) {
						match = true;
					} else {
						match = false;
						break;
					}
				} catch (Exception e) {
					e.printStackTrace();
					match = false;
				}
			}
			if(match) {  
                data.add(receptor);  
            }
		}
		//sort  
        if(sortField != null) {  
            Collections.sort(data, new LazySorterReceptor(sortField, sortOrder));  
        }  
  
        //rowCount  
        int dataSize = data.size();  
        this.setRowCount(dataSize);  
  
        //paginate  
        if(dataSize > pageSize) {  
            try {  
                return data.subList(first, first + pageSize);  
            }  
            catch(IndexOutOfBoundsException e) {  
                return data.subList(first, first + (dataSize % pageSize));  
            }  
        }  
        else {  
            return data;  
        }  
	}
}
